import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // 如何在白名单里，直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 没有token
  if (!store.getters.token) {
    await store.dispatch('user/logout')
    return
  }

  // 有token
  if (!store.getters.userInfo) {
    await store.dispatch('user/getAdminUserInfo')

    next({
      ...to,
      replace: true // 重新了一次页面，避免重新进页面历史重复的问题
    })
    return
  }

  next()
})

router.afterEach((to, from) => {
  // finish progress bar
  NProgress.done()
  // set page title
  document.title = getPageTitle(to.meta.title)
})
